import java.util.Arrays;

public class MyArrayList implements IList {
    private static final int DEFAULT_CAPACITY = 10;
    private int[] array;
    private int size = 0;

    MyArrayList(){
        this.array = new int[DEFAULT_CAPACITY];
    }

    boolean isEmpty(){
        return size == 0;
    }

    boolean isFull(){
        return size == array.length;
    }

    void grow(){
        array = Arrays.copyOf(array,array.length*2);
    }

    void checkPos(int pos) throws PosIllegalException{
        if(pos<0||pos>=size){
            throw new PosIllegalException("pos位置不合法！");
        }
    }

    void checkEmpty() throws EmptyException{
        if(isEmpty())
            throw new EmptyException("顺序表为空！");
    }

    @Override
    public void add(int e) {
        if(isFull())
            grow();
        array[size] = e;
        size++;
    }

    @Override
    public void add(int pos, int e) {
        try{
            checkPos(pos);
            if(isFull())
                grow();
            for (int i = size - 1; i >= pos; i--) {
                array[i+1]=array[i];
            }
            array[pos] = e;
            size++;
        }catch (PosIllegalException p){
            p.printStackTrace();
        }
    }

    public boolean contains(int toFind){
        for (int i : array) {
            if (toFind == i)
                return true;
        }
        return false;
    }
    @Override
    public void set(int pos, int e) {
        checkPos(pos);
        array[pos] = e;
    }

    @Override
    public void remove(int e)throws EmptyException {
        try{
            checkEmpty();
            int pos = indexOf(e);
            if(pos==-1){
                System.out.println("该元素不存在");
                return ;
            }
            for (int i = pos ; i <size - 1 ; i++) {
                array[i] = array[i+1];
            }
            size--;
        }catch (EmptyException ex){
            ex.printStackTrace();
        }
    }

    @Override
    public int indexOf(int e) {
        for (int i = 0; i < size; i++) {
            if(array[i] == e)
                return i;
        }
        return -1;
    }

    @Override
    public int getElement(int pos) {
        try{
            checkEmpty();
            checkPos(pos);
            return array[pos];
        }catch (PosIllegalException | EmptyException p){
            p.printStackTrace();
        }
        return 0;
    }

    @Override
    public void clear() {
        size = 0;
    }

    @Override
    public void display() {
        try{
            checkEmpty();
            for (int i = 0; i < size; i++) {
                System.out.print(array[i]+" ");
            }
            System.out.println(" ");
        }catch (EmptyException e){
            e.printStackTrace();
        }
    }

    @Override
    public int getSize() {
        return size;
    }
}
